#include "uart_manager.h"
#include "command.h"
#include "command_manager.h"
#include <stdio.h>
#include <string.h>
#include "ohos_init.h"
#include "cmsis_os2.h"

#define TASK_STACK_SIZE 1024 * 4
#define TASK_PRIO 20
#define UART_BUFF_SIZE 100

static const char *TAG = "IotUartTask Test";

void IotUartTask(void)
{
    ESP_LOGI(TAG, "IotUartTask enter\n");
    int32_t ret;
    char response[UART_BUFF_SIZE] = {0};

    // 创建命令管理器
    CommandManager *manager = create_command_manager();
    if (manager == NULL)
    {
        ESP_LOGI(TAG, "Failed to create command manager\n");
        osThreadExit();
    }

    // 添加多个 AT 指令，支持变量拼接
    add_command(manager, create_command("AT+W=%d %d %d\r\n", 1, 2, 3));
    add_command(manager, create_command("AT+R=%s %d\r\n", "test", 42));
    add_command(manager, create_command("AT+C=?\r\n"));
    add_command(manager, create_command("AT+D=%d\r\n", 1));

    while (1)
    {
        // 执行指定的命令
        ESP_LOGI(TAG, "IotUartTask excute first cmd\n");
        execute_command(manager, 0, response, UART_BUFF_SIZE); // 执行第1个命令
        memset(response, 0, UART_BUFF_SIZE);                   // 清空响应缓冲区
        osDelay(1000);                                         // 等待1秒

        ESP_LOGI(TAG, "IotUartTask excute second cmd\n");
        execute_command(manager, 1, response, UART_BUFF_SIZE); // 执行第2个命令
        memset(response, 0, UART_BUFF_SIZE);                   // 清空响应缓冲区
        osDelay(1000);                                         // 等待1秒

        // 可以根据需要执行其他命令,如
        ESP_LOGI(TAG, "IotUartTask excute third cmd\n");
        execute_command(manager, 2, response, UART_BUFF_SIZE); // 执行第2个命令
        memset(response, 0, UART_BUFF_SIZE);                   // 清空响应缓冲区
        osDelay(1000);                                         // 等待1秒

        ESP_LOGI(TAG, "IotUartTask excute forth cmd\n");
        execute_command(manager, 3, response, UART_BUFF_SIZE); // 执行第2个命令
        memset(response, 0, UART_BUFF_SIZE);                   // 清空响应缓冲区
        osDelay(1000);                                         // 等待1秒
    }

    // 释放命令管理器
    free_command_manager(manager);
    ESP_LOGI(TAG, "IotUartTask exit\n");
    osThreadExit();
}

void IotUartDemo(void)
{
    osThreadAttr_t attr = {
        .name = "Iot_UART_TASK_NAME",
        .attr_bits = 0U,
        .cb_mem = NULL,
        .cb_size = 0U,
        .stack_mem = NULL,
        .stack_size = TASK_STACK_SIZE,
        .priority = TASK_PRIO,
    };

    if (osThreadNew((osThreadFunc_t)IotUartTask, NULL, &attr) == NULL)
    {
        ESP_LOGI(TAG, "Failed to create thread!\n");
    }
}

APP_FEATURE_INIT(IotUartDemo);